<!--
  - Copyright (c) 2018.
  - 北京九思金信科技有限公司对该文件内容保留所有权利。
  - 未经许可，不得私自拷贝、传播、发布、引用该文件内容，违者将被追究法律责任。
  -->

<template>
    <el-card shadow="never" body-style="padding: 0px 24px 24px 24px">
        <el-row style="padding: 16px 0px; justify-content: center">
            <el-button type="info"
                       @click="goBack()"
                       style="padding: 7px 23px;" round>
                <span style="font-size: 16px;line-height: 20px">返回客户列表</span>
            </el-button>
        </el-row>
        <el-row>
            <el-col align="left" style="line-height: 36px">
                <span style="font-size: 14px;color: #747778">基础关键资料</span>
            </el-col>
        </el-row>
        <div class="cardBackColor">
            <el-form ref="person"
                     :model="person"
                     :rules="rules"
                     style="text-align: left;padding: 48px 12px 0px 12px"
                     inline>
                <el-row style="padding-left: 12px;padding-right: 12px;padding-bottom: 24px">
                    <el-col :md="12" :lg="12">
                        <el-form-item label="客户名称" prop="customerName">
                            <ft-input v-model="person.customerName"
                                      editing=true></ft-input>
                        </el-form-item>
                    </el-col>

                    <el-col :md="12" :lg="12">
                        <el-form-item label="证件类型" prop="identityType">
                            <ft-enum-select v-model="person.identityType"
                                            service-name="lss-customer"
                                            type-name="personalType"
                                            placeholder="请选择证件类型"
                                            size="small"
                                            editing
                                            @change="identityTypeChange(person.identityType)">
                            </ft-enum-select>
                        </el-form-item>
                    </el-col>

                    <el-col :md="12" :lg="12">
                        <el-form-item label="证件号码" prop="identityNo" ref="identityNo">
                            <ft-input v-model="person.identityNo"
                                      :editing="initEdit"></ft-input>
                        </el-form-item>
                    </el-col>

                    <el-col :md="12" :lg="12">
                        <el-form-item label="主办客户经理" prop="mainManagerId">
                            <ft-user v-model="person.mainManagerId"
                                     :editable="initEdit"
                                     :customerManagerId="person.mainManagerId"
                                     @matchedOption="mainManagerChangeMatched"
                                     @unmatchedOption="mainManagerChangeMatched"/>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :lg="12">
                        <el-form-item label="协办客户经理" prop="viceManagerId">
                            <ft-user-with-filter ref="viceManagerRef"
                                                 v-model="person.viceManagerId"
                                                 :editable="initEdit"
                                                 :customer-manager-id="person.viceManagerId"
                                                 @matchedOption="viceManagerChangeMatched"
                                                 @unmatchedOption="viceManagerChangeMatched">

                            </ft-user-with-filter>
                        </el-form-item>
                    </el-col>

                    <el-col :md="12" :lg="12">
                        <el-form-item label="所属部门" prop="deptName">
                            <ft-input :editing="false" v-model="person.deptName"></ft-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :md="12" :lg="12">
                        <el-upload :http-request="uploadApplyBook"
                                   action="/joys-rest/joys-file/files/source"
                                   :file-list="fileList"
                                   :show-file-list='false'>
                            <el-button type="text">点击此处，上传融资租赁业务申请书</el-button>
                        </el-upload>
                    </el-col>
                </el-row>

                <hr style="background-color: #EDEDED;border: none;height: 1px;margin: 0px"/>

                <el-row style="padding:16px 0px">
                    <el-col align="right">
                        <el-button size="mini"
                                   @click="goBack()">取消
                        </el-button>
                        <el-button type="primary"
                                   size="mini"
                                   :disabled="saveStatus"
                                   style="margin-left: 24px;margin-right: 36px"
                                   @click="onSave()">保存
                        </el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </el-card>

</template>

<script>

    import uuid from 'uuid'
    import FtInput from "../ft/FtInput"
    import FtUser from "../ft/FtUser"
    import FtUserWithFilter from "../ft/FtUserWithFilter";
    import {existsCustName, existsCustNo, identityFormat} from "@/pages/pc/assets/js/validate/rule.js"

    export default {
        name: "CustomerCorpAdd",
        props: {
            propsBind: {
                //展示页面
                currentPage: {
                    default: 1
                },
                //页面条数
                pageSize: {
                    default: 8
                }
            }
        },
        components: {FtUserWithFilter, FtInput, FtUser},
        data() {
            //根据客户名称判断是否已存在
            let validateCustName = (rule, value, callback) => {
                const _this = this
                if (value && value != '') {
                    existsCustName(_this, rule, value, callback)
                } else {
                    callback()
                }
            }
            //根据证件号码判断是否已存在
            let validateCustNum = (rule, value, callback) => {
                if (this.person.identityType == '') {
                    callback(new Error('请选择客户证件类型'))
                } else {
                    if (value && value != '') {
                        if (!identityFormat(this.person.identityType, value)) {
                            callback(new Error('输入证件号码不合法'))
                        } else {
                            existsCustNo(this, rule, value, callback)
                        }
                    } else {
                        callback()
                    }
                }
            }
            return {
                // 新增客户id
                customerId: '',
                // 保存按钮是否可点击, true不可点击, false可点击
                saveStatus: false,
                // 是否已上传业务申请书
                uploadStatus: false,
                // 上传的文件
                fileList: [],
                // 上传的文件名称
                fileName: '',
                initEdit: true,
                condition: '1',
                person: {
                    customerId: '',
                    customerName: '',
                    identityType: 'IDENTITY_CARD',
                    identityNo: '',
                    mainManagerId: null,
                    viceManagerId: null,
                    deptId: '',
                    mainManagerName: null,
                    viceManagerName: null,
                    deptName: '',
                },
                rules: {
                    customerName: [
                        {required: true, message: '客户名称不能为空', trigger: 'blur'},
                        {max: 30, message: '客户名称需在30字内', trigger: 'blur'}
                    ],
                    identityType: [
                        {required: true, message: '证件类型不能为空', trigger: 'blur'},
                    ],
                    identityNo: [
                        {required: true, message: '证件号码不能为空', trigger: 'blur'},
                        {validator: validateCustNum, trigger: 'blur'}
                    ],
                    mainManagerId: [
                        {required: true, message: '主办客户经理不能为空'},
                    ],
                    viceManagerId: [
                        {required: true, message: '协办客户经理不能为空'},
                    ],
                    deptName: [
                        {required: true, message: '所属部门不能为空', trigger: 'blur'},
                    ],
                },
            }
        },
        watch: {
            person: {
                handler(val) {
                    // 过滤条件
                    let viceManagerFilter = ''
                    if (val.deptId) {
                        viceManagerFilter = 'dt.dept_id = \'' + val.deptId + '\''
                    }
                    this.$refs.viceManagerRef.load(viceManagerFilter)
                },
                deep: true,
            },
        },
        mounted() {
            this.loadCustomerManager()
        },
        methods: {

            onSave() {
                this.saveStatus = true
                if (!this.uploadStatus) {
                    this.$message.error('请先上传业务申请书!')
                    this.saveStatus = false
                    return;
                }
                this.person.customerId = this.customerId
                this.person.customerType = 'PERSONAL'
                this.$refs.person.validate((valid) => {
                    if (valid) {
                        this.$http.put('/joys-rest/lss-customer/custInfo/person', this.person, {
                            params: {
                                sourceModule: "基础关键资料",
                            }
                        }).then(resp => {
                            this.person = resp.body
                            this.saveStatus = false
                            this.$emit('returnValue', {
                                switchShow: 'person',
                                propsBind: this.propsBind,
                                customerId: this.person.customerId,
                                initEdit: true
                            })
                        }, resp => {
                            this.saveStatus = false
                            this.$message.error(resp.body)
                        })
                    } else {
                        this.saveStatus = false
                        return false
                    }
                })
                this.saveStatus = false
            },
            goBack() {
                this.$refs.person.clearValidate()
                this.$emit('returnValue', {
                    switchShow: 'cust-list',
                    propsBind: this.propsBind,
                    customerId: null,
                    initEdit: false
                });
            },
            //选择证件类型后清空证件号码及证件号码校验结果
            identityTypeChange(val) {
                this.$set(this.person, "identityNo", '')
                this.$refs["identityNo"].clearValidate()
            },
            //主办客户经理回调
            mainManagerChangeMatched(val) {
                this.$set(this.person, 'mainManagerId', val.userId)
                this.$set(this.person, 'deptName', val.deptName)
                this.$set(this.person, 'deptId', val.deptId)
                this.person.mainManagerName = val.userName
            },
            //协办客户经理回调
            viceManagerChangeMatched(val) {
                this.person.viceManagerId = val.userId
                this.$set(this.person, 'viceManagerId', val.userId)
                this.person.viceManagerName = val.userName
            },
            //加载默认主办，部门
            loadCustomerManager() {
                this.$http.get('/joys-rest/lss-customer/custInfo').then(
                    resp => {
                        this.person = resp.body
                    },
                    resp => {
                        return false;
                    }
                )
            },

            // 上传业务申请书
            uploadApplyBook(item) {
                if (this.uploadStatus === true) { // 已经上传过了
                    this.$confirm('您当前已上传了一个业务申请书, 继续上传将会覆盖上一个业务申请书, 是否继续？', '警告', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        // 1.先删除上一个已上传的文件
                        const url = '/joys-rest/joys-file/files/source'
                        this.$http.delete(url, {
                            params: {
                                sourceType: 'CUSTOMER',
                                sourceId: this.customerId,
                                name: this.fileName,
                            },
                        }).then(
                            resp => {
                                // this.$message.success('删除历史文件成功')
                                // 2.重新上传
                                this.uploadData(item)
                            },
                            resp => {
                                this.$message.error('删除历史文件失败')
                            }
                        )
                    })
                } else { // 没有上传过
                    this.uploadData(item)
                }
            },
            // 上传文件
            uploadData(item) {
                if (!this.customerId) {
                    this.customerId = uuid()
                }
                const url = '/joys-rest/joys-file/files/source'
                // FormData对象用以将数据编译成键值对,其主要用于发送表单数据，
                // 但亦可用于发送带键数据(keyed data)，而独立于表单使用
                let formData = new FormData();
                formData.append('file', item.file)
                this.$http.put(url, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'AUTH-TOKEN': localStorage.getItem('AUTH-TOKEN')
                    },
                    params: {
                        sourceId: this.customerId,
                        sourceType: 'CUSTOMER',
                        path: '/doc/generate/客户维护/' + this.customerId,
                        dataType: 'file',
                        category: '融资业务申请书',
                        sourceMode: 'MANUAL',
                        last: true
                    }
                }).then(
                    resp => {
                        this.fileName = resp.body.fullName
                        this.uploadStatus = true
                        this.$message.success('上传成功')
                    }, resp => {
                        this.$message.error('上传失败')
                    }
                )
            },
        },


    }
</script>

<style scoped>
    .cardBackColor {
        background-color: #F4F8F9
    }
</style>
